
const config = require('ym-Config');
const querystring = require("querystring");
const Events = require('ym-Events')
const NullFunc = function(){}

var isCheckLogining = false;

function dispatch(func,d1,d2){
    try{
        func(d1,d2);
    }catch(e){
        console.error('Http回调函数执行出错:',e);
    }
}

var Http = {
    setOptions(option){
        if(!option._id || typeof(option.token) == 'undefined'){
            cc.error('没有ID 或者token')
            return;
        }
        this.options = option;
    },
    
    checkLogin(options){
        if(isCheckLogining){
            cc.log('自动登陆中，无需继续发送')
            return;
        }
        var defaultOptions = {
            deltaTime:3,
            cb : NullFunc
        }
        Object.assign(defaultOptions,options);

        isCheckLogining = true;
        Events.on('checkLogin',function(err,res){
            if(err){
                cc.log('err:',err)
            } else {
                Events.removeAllListeners('checkLogin')
                defaultOptions.cb(res);
            }
        },this)
        
        this.loginGet({
            router:'checkLogin',
            data : options.data || {},
            eventName:'checkLogin',
            reconnect:true
        });
    },

    loginGet(options){
        !options.data && (options.data = {})
        if(this.options && this.options._id){
            Object.assign(options.data,this.options)
            this.get(options)
        } else {
            cc.error('还未设置登陆参数')
        }
    },

    get: function (options) {
        var defaultOptions = {
            path:'/game/gameUser', //路径
            router : '', //路由
            data :{},   //数据
            cb:function(){},
            eventName:'',   //需要派发的事件名称
            reconnect:false //失败时是否重新发送
        }
        var options = Object.assign(defaultOptions,options)
        options.router.length && (Object.assign(options.data,{router:options.router}))

        let url = `${config.httpRootUrl}${options.path}?${querystring.stringify(options.data)}`;
        cc.log('httpurl:',url);
        const xhr = cc.loader.getXMLHttpRequest();
        xhr.open("GET", url, true);
        var timeout = setTimeout(function(){
            xhr['abort'] && xhr.abort();
        },30000)
        xhr.onerror = function(err){
            if(options.reconnect){
                setTimeout(function(){
                    Http.get(options)
                },1500)
            }else {
                !!options.eventName && Events.emit(options.eventName,err,null)
                dispatch(options.cb,err,null)
            }
        }
        xhr.onreadystatechange = () => {
            if(xhr.readyState === 4){
                clearTimeout(timeout);
                if(xhr.status >= 200 && xhr.status < 300){
                    // cc.log('resp:'+xhr.response)
                    var data = null;
                    try {
                        data = JSON.parse(xhr.response);
                    } catch (e) {
                        !!options.eventName && Events.emit(options.eventName,e,null)
                        dispatch(options.cb,e,null)
                        cc.error("err:" + e);
                        return;
                    }
                    if (data.code === 200) {
                        !!options.eventName && Events.emit(options.eventName,null,data.data)
                        dispatch(options.cb,null,data.data)
                    } else {
                        !!options.eventName && Events.emit(options.eventName,data.code,data.data)
                        dispatch(options.cb,data.code,data.data)
                        cc.log('登陆失败！'+data);
                    }
                } else if(options.reconnect){
                    setTimeout(function(){
                        Http.get(options)
                    },1500)
                }
                else {
                    Events.emit(options.eventName,xhr.status,null)
                }
            }
        }
        
        xhr.send();
    },
    post: function (options) {
        var defaultOptions = {
            path:'/game/gameUser',
            router : '',
            data :{},
            cb:function(){},
            eventName:'',
            reconnect:false
        }
        options = Object.assign(defaultOptions,options)
        !!options.router && (Object.assign(options.data,{router:options.router}))

        var sendstr = querystring.stringify(options.data);
        var xhr = cc.loader.getXMLHttpRequest();

        xhr.open("POST", `${config.httpRootUrl}${options.path}`, true);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

        var timeout = setTimeout(function () {
            xhr['abort'] && xhr.abort();
        }, 30000);
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status <= 300)) {
                clearTimeout(timeout);
                // cc.log('resp:' + xhr.response)
                var data = null;
                try {
                    data = JSON.parse(xhr.response);
                } catch (e) {
                    Events.emit(options.eventName,e,null)
                    dispatch(options.cb,e,null)
                    cc.error("err:" + e);
                    return;
                }
                if (data.code === 200) {
                    Events.emit(options.eventName,null,data.data)
                    dispatch(options.cb,null,data.data)
                    // cb(null,data.data);
                } else {
                    Events.emit(options.eventName,data.code,data.data)
                    dispatch(options.cb,data.code,data.data)
                    cc.log('登陆失败！'+data);
                }
            }
        };
        xhr.send(sendstr);
    },
}

module.exports = Http;